package ciyuan.dataStore;

import ciyuan.QQLogin;
import ciyuan.wrap.Wrapper;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.locks.ReentrantLock;

public class PlayerLoginTime {

    private final File dataFile;
    private Object config;
    private final ReentrantLock lock;

    public PlayerLoginTime(File dataFile) {
        this.dataFile = dataFile;
        this.lock = new ReentrantLock(true);
        try {
            if (!dataFile.exists()) {
                dataFile.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.config = Wrapper.INSTANCE.loadConfiguration(dataFile);
    }

    private void save() {
        lock.lock();
        try {
            Wrapper.INSTANCE.saveConfiguration(config, dataFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        lock.unlock();
    }

    private void load() {
        lock.lock();
        this.config = Wrapper.INSTANCE.loadConfiguration(dataFile);
        lock.unlock();
    }

    public boolean isTimeout(String playerName) {
        load();
        long recordTime = Wrapper.INSTANCE.configGetLong(config, playerName);
        Wrapper.INSTANCE.logMsg(
            "IP过期判断 记录时间:" + recordTime + ",当前时间:" + System.currentTimeMillis() + ",差值:" + (System.currentTimeMillis() - recordTime));
        return System.currentTimeMillis() - recordTime > QQLogin.config.IpTimeoutSeconds * 1000;
    }

    public void setTime(String playerName) {
        Wrapper.INSTANCE.configSetValue(config, playerName, System.currentTimeMillis());
        save();
    }
}
